﻿using System;
using System.Configuration.Provider;
using System.Linq;
using System.Web.Security;
using reDoo.Data;
using reDoo.Model;
using StructureMap;

namespace reDoo.Security
{
    public class OpenRoleProvider : RoleProvider
    {
        #region Declarations / Fields

        private const string DEFAULT_PROVIDER_NAME = "reDoo OpenRoleProvider";
        private const string DEFAULT_PROVIDER_DESCRIPTION = "Role provider implementations that can be used for custom data stores.";

        private readonly IMemberRepository memberRepository;
        private readonly IRoleRepository roleRepository;

        #endregion

        #region Constructors

        public OpenRoleProvider()
            : this(ObjectFactory.GetInstance<IMemberRepository>(), ObjectFactory.GetInstance<IRoleRepository>())
        {
        }

        public OpenRoleProvider(IMemberRepository memberRepository, IRoleRepository roleRepository)
        {
            this.memberRepository = memberRepository;
            this.roleRepository = roleRepository;
        }

        #endregion

        #region Initilization

        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception>
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (string.IsNullOrEmpty(name))
                name = DEFAULT_PROVIDER_NAME;

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", DEFAULT_PROVIDER_DESCRIPTION);
            }

            base.Initialize(name, config);
        }

        #endregion

        #region Get role data

        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        /// <param name="username">The user name to search for.</param><param name="roleName">The role to search in.</param>
        public override bool IsUserInRole(string username, string roleName)
        {
            var user = memberRepository.GetByUsername(username);

            var userIsInRole = user.Roles.ToList().Exists(r => r.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase));

            return userIsInRole;
        }

        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        /// </returns>
        /// <param name="username">The user to return a list of roles for.</param>
        public override string[] GetRolesForUser(string username)
        {
            var user = memberRepository.GetByUsername(username);

            return user.Roles.Select(r => r.Name).ToArray();
        }

        /// <summary>
        /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
        /// </summary>
        /// <returns>
        /// true if the role name already exists in the data source for the configured applicationName; otherwise, false.
        /// </returns>
        /// <param name="roleName">The name of the role to search for in the data source.</param>
        public override bool RoleExists(string roleName)
        {
            return this.roleRepository.Find(r => r.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase)).Count() > 0;
        }

        /// <summary>
        /// Gets a list of users in the specified role for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the users who are members of the specified role for the configured applicationName.
        /// </returns>
        /// <param name="roleName">The name of the role to get the list of users for.</param>
        public override string[] GetUsersInRole(string roleName)
        {
            var roleMembers = this.roleRepository.GetByName(roleName).Members;
            return roleMembers.Select(m => m.Username).ToArray();
        }

        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the roles stored in the data source for the configured applicationName.
        /// </returns>
        public override string[] GetAllRoles()
        {
            return this.roleRepository.GetAll().Select(r => r.Name).ToArray();
        }

        #endregion

        #region Add role data

        /// <summary>
        /// Adds a new role to the data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to create.</param>
        public override void CreateRole(string roleName)
        {
            if (roleName.Contains(","))
                throw new ArgumentException("Role names cannot contain commas.");

            if (RoleExists(roleName))
                throw new ProviderException("Role name already exists.");

            var role = new Role { Name = roleName };

            this.roleRepository.Add(role);

            this.roleRepository.SaveChanges();
        }

        /// <summary>
        /// Adds the specified user names to the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="usernames">A string array of user names to be added to the specified roles. </param><param name="roleNames">A string array of the role names to add the specified user names to.</param>
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            if (roleNames.Any(rolename => !RoleExists(rolename)))
                throw new ProviderException("Role name not found.");

            foreach (string username in usernames)
            {
                if (username.Contains(","))
                    throw new ArgumentException("User names cannot contain commas.");

                if (roleNames.Any(rolename => IsUserInRole(username, rolename)))
                    throw new ProviderException("User is already in role.");
            }

            var roles = roleRepository.Find(r => roleNames.Contains(r.Name));
            var members = this.memberRepository.Find(m => usernames.Contains(m.Username));

            foreach (var role in roles)
            {
                foreach (var member in members)
                {
                    role.Members.Add(member);
                }
            }

            this.roleRepository.SaveChanges();
        }

        #endregion

        #region Delete role data

        /// <summary>
        /// Removes a role from the data source for the configured applicationName.
        /// </summary>
        /// <returns>
        /// true if the role was successfully deleted; otherwise, false.
        /// </returns>
        /// <param name="roleName">The name of the role to delete.</param><param name="throwOnPopulatedRole">If true, throw an exception if <paramref name="roleName"/> has one or more members and do not delete <paramref name="roleName"/>.</param>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (!RoleExists(roleName))
                throw new ProviderException("Role does not exist.");

            if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0)
                throw new ProviderException("Cannot delete a populated role.");

            this.roleRepository.DeleteByName(roleName);
            this.roleRepository.SaveChanges();

            return true;

        }

        /// <summary>
        /// Removes the specified user names from the specified roles for the configured applicationName.
        /// </summary>
        /// <param name="usernames">A string array of user names to be removed from the specified roles. </param><param name="roleNames">A string array of role names to remove the specified user names from.</param>
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            if (roleNames.Any(rolename => !RoleExists(rolename)))
                throw new ProviderException("Role name not found.");

            foreach (string username in usernames)
            {
                if (roleNames.Any(rolename => !IsUserInRole(username, rolename)))
                    throw new ProviderException("User is not in role.");
            }

            var roles = roleRepository.Find(r => roleNames.Contains(r.Name));
            var members = this.memberRepository.Find(m => usernames.Contains(m.Username));

            foreach (var member in members)
            {
                foreach (var role in roles)
                    member.Roles.Remove(role);
            }

            this.memberRepository.SaveChanges();
        }

        #endregion

        #region Overrides of RoleProvider

        /// <summary>
        /// Gets an array of user names in a role where the user name contains the specified user name to match.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the users where the user name matches <paramref name="usernameToMatch"/> and the user is a member of the specified role.
        /// </returns>
        /// <param name="roleName">The role to search in.</param><param name="usernameToMatch">The user name to search for.</param>
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            var role = this.roleRepository.GetByName(roleName);
            var membersThatMatch = role.Members.Where(m => m.Username.Contains(usernameToMatch));

            return membersThatMatch.Select(m => m.Username).ToArray();
        }

        /// <summary>
        /// Gets or sets the name of the application to store and retrieve role information for.
        /// </summary>
        /// <returns>
        /// The name of the application to store and retrieve role information for.
        /// </returns>
        public override string ApplicationName { get; set; }

        #endregion
    }
}
